from flask import Flask, request, jsonify, make_response

app = Flask(__name__)

# 模拟数据库，存储用户信息、商品信息和订单信息
users = {
    'user1': {'userid': 'user1', 'password': 'pass1', 'name': 'User One','code':{'errorcode':0},'num':[1,2,3,4],'dict':[{'age':1},{'age':2}]},
    'user2': {'userid': 'user2', 'password': 'pass2', 'name': 'User Two'}
}

products = {
    'product1': {'productid': 'product1', 'name': 'Product One', 'price': 10.99},
    'product2': {'productid': 'product2', 'name': 'Product Two', 'price': 20.99}
}

orders = {
    'user1': [],
    'user2': []
}

# 登陆接口，表单入参，返回Cookie信息
@app.route('/login', methods=['POST'])
def login():
    userid = request.form.get('userid')
    password = request.form.get('password')

    if userid in users and users[userid]['password'] == password:
        response = make_response(jsonify(users[userid]))
        response.set_cookie('userid', userid)  # 设置Cookie
        return response
    else:
        return jsonify({'message': 'Invalid credentials'}), 200

# 获取个人信息接口，从Cookie中获取userid
@app.route('/profile', methods=['GET'])
def profile():
    userid = request.cookies.get('userid')  # 从Cookie中获取userid

    if userid in users:
        return jsonify(users[userid])
    else:
        return jsonify({'message': 'User not found'}), 404

# 查询商品信息接口
@app.route('/get_product', methods=['GET'])
def get_product():
    productid = request.args.get('productid')

    if productid in products:
        return jsonify(products[productid])
    else:
        return jsonify({'message': 'Product not found'}), 404

# 提交订单接口，JSON入参，使用Cookie中的userid
@app.route('/submit_order', methods=['POST'])
def submit_order():
    data = request.json
    userid = request.cookies.get('userid')  # 从Cookie中获取userid
    productid = data.get('productid')
    order = {'productid': productid, 'userid': userid}

    if userid in users and productid in products:
        orders[userid].append(order)
        return jsonify({'message': 'Order submitted successfully'})
    else:
        return jsonify({'message': 'User or product not found'}), 404

# 查询订单接口，从Cookie中获取userid
@app.route('/get_orders', methods=['GET'])
def get_orders():
    userid = request.cookies.get('userid')  # 从Cookie中获取userid

    if userid in users:
        return jsonify({'orders': orders[userid]})
    else:
        return jsonify({'message': 'User not found'}), 404

if __name__ == '__main__':
    app.run(host='0.0.0.0',port=5000)
